package No1_100.No11_20.RemoveNthNodeFromEndofList_19;

import No1_100.No1_10.AddTwoNumbers_2.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode lsListNode0 = head;
        ListNode lsListNode1 = head;
        ListNode ret = head;
        int i = 0;
        while (head != null) {
			head = head.next;
			i++;
			if (i > n) {
				lsListNode1 = lsListNode0;
				lsListNode0 = lsListNode0.next;
			}
		}
        if (lsListNode0 == ret) {
			ret = ret.next;
		}
        else{
        	lsListNode1.next = lsListNode0.next;
        }
    	return ret;
    }
    
    public static void main(String args[]) {
		ListNode lsListNode = new ListNode(0);
		ListNode retListNode = lsListNode;
		lsListNode.val = 1;
		ListNode retListNode2 = new ListNode(0);
		retListNode2.val = 2;
		lsListNode.next = retListNode2;
		ListNode retListNode4 = new ListNode(0);
		retListNode4.val = 3;
		retListNode2.next = retListNode4;
		ListNode retListNode3 = new ListNode(0);
		retListNode3.val = 1;
		ListNode ret = removeNthFromEnd(retListNode,1);
		while(ret!=null){
			System.out.print(ret.val);
			ret = ret.next;
		}
		
		System.out.println("\nok");
		
	}
}